package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.domain.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    /**
     * 发送短信验证码
     *
     * @param session
     * @param map
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session,@RequestBody Map<String,String> map){
        //1.获取手机号
        String phone = map.get("phone");
        if (redisTemplate.opsForValue().get(phone)!=null){
            throw new CustomException("验证码还没过期");
        }
        //2.随机生成验证码
//        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        String code = "123456";
        //3.调用工具类发送验证码
//        SMSUtils.sendMessage("ygd博客","SMS_460780142",phone,code);
        // 4.把验证码存入session中  key:手机号 value:验证码
//        session.setAttribute(phone,code);
        //将生成的验证码存到缓存中,设置过期时间
        redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
        return R.success("发送成功");
    }

    /**
     * 登录
     *
     * @param session
     * @param map
     * @return
     */
    @PostMapping("/login")
    public R<String> login(HttpSession session,@RequestBody Map<String,String> map){
        //1. 获取用户输入手机号，验证码
        String phone = map.get("phone");
        String code = map.get("code");
        //2. 获取session中的验证码
        //Object codeInSession = session.getAttribute(phone);
        //从Redis中获取缓存中的验证码
        Object codeInSession = redisTemplate.opsForValue().get(phone);
        //3. 比对用户输入的验证码和session中的验证码
        if (codeInSession == null || !codeInSession.equals(code)) {
            //3.1 如果不一致，抛出业务异常
            throw new CustomException("验证码错误");
        }
        //4. 根据手机号判断用户是否存在
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,phone);
        User user = userService.getOne(lqw);
        if (user == null) {
            //4.1 如果不存在？注册（添加到数据库）
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }
        //5. 判断用户状态
        if (user.getStatus()==0) {
            //5.1 如果已禁用，不允许，抛出业务异常
            throw new CustomException("用户已被禁用");
        }
        //6. 用户登陆成功，存入session
        session.setAttribute("user",user.getId());
        //7. 移除session中的验证码
        //session.removeAttribute(phone);
        // 登录成功,删除缓存中的验证码
        redisTemplate.delete(phone);
        return R.success("登陆成功");
    }

    /**
     * 用户退出
     *
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpSession session){
        session.removeAttribute("user");
        return R.success("退出成功");
    }
}
